#include "Socket.hpp"
#include <pthread.h>
#include <functional>

typedef function<void(int)> func_t;

class TcpSever;
class threaddata
{
public:
    threaddata(int acceptedsocket,TcpSever* sever)
    :_accepted_socket(acceptedsocket)
    ,_sever(sever)
    {}
    ~threaddata()
    {}
public:
    int _accepted_socket;
    TcpSever* _sever;
};

class TcpSever
{
public:
    static void* threadroutine(void* args)
    {
        pthread_detach(pthread_self());
        threaddata* td = (threaddata*)args;
        td->_sever->Excute(td->_accepted_socket);
        close(td->_accepted_socket);
        delete td;
        
        return nullptr;
    }
    TcpSever(uint16_t port,string ip = "0.0.0.0")
    {
        _listen_socket = _sock.Socket();
        _sock.Bind(_listen_socket,port,ip);
        _sock.Listen(_listen_socket);
    }
    void start()
    {
        while(1)
        {
            //这两个参数是为了获取客户端ip和端口
            uint16_t port;
            string ip;
            int accepted_sock = _sock.Accept(_listen_socket,&ip,&port);
            if(accepted_sock < 0)
            {
                continue;
            }
            pthread_t tid;
            threaddata* td = new threaddata(accepted_sock, this);
            pthread_create(&tid,nullptr,threadroutine,(void*)td);
        }
    }

    void BindService(func_t func)
    {
        _func = func;
    }
    void Excute(int accepted_sock)
    {
        _func(accepted_sock);
    }
    ~TcpSever()
    {}
private:
    int _listen_socket;
    Sock _sock;
    func_t _func;
};